import { extend } from 'lodash';
import { NzSafeAny } from 'ng-zorro-antd/core/types';

export class DashboardWidgetsConnectionManager {
  private _connections: NzSafeAny = {};
  get connections(): NzSafeAny {
    return this._connections;
  }

  updateConnections(names: NzSafeAny[]): void {
    let newConnections: NzSafeAny;
    names.forEach(config => {
      let newName = config.name,
        previousName = config.previousName;

      if (newName == null) {
        delete this.connections()[newName];
      } else if (previousName == null) {
        newConnections[newName] = this.getConnectionByName(newName);
      } else {
        newConnections[newName] = this.getConnectionByName(previousName);
        delete this.connections[previousName];
      }
    });

    extend(this._connections, newConnections);
  }

  getConnectionByName(name: string): NzSafeAny {
    if (name == null) {
      return {};
    }

    if (this.connections[name] == null) {
      this.connections[name] = {};
    }

    return this.connections[name];
  }
}
